package gl.texture;

import org.lwjgl.opengl.GL11;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public abstract class TextureAtlas<T> implements AutoCloseable {

    protected final int target, binding, textureId;
    protected final int width, height;
    protected Map<String, T> coordMap = new HashMap<>();

    protected TextureAtlas(int target, int binding, int textureId, int width, int height) {
        this.target = target;
        this.binding = binding;
        this.textureId = textureId;
        this.width = width;
        this.height = height;
    }

    protected void put(String name, T coord) {
        coordMap.put(name, coord);
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public Optional<T> get(String name) {
        if (coordMap.containsKey(name)) {
            return Optional.of(coordMap.get(name));
        }
        return Optional.empty();
    }

    public boolean contains(String name) {
        return coordMap.containsKey(name);
    }

    public void bind() {
        GL11.glBindTexture(target, textureId);
    }

    public void unbind() {
        if (GL11.glGetInteger(binding) == textureId) {
            GL11.glBindTexture(target, 0);
        }
    }

    public void remove() {
        unbind();
        GL11.glDeleteTextures(textureId);
    }

    @Override
    public void close() {
        remove();
    }
}
